package com.hingsmy.pma.security;

import org.hibernate.boot.model.relational.Database;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    DataSource dataSource;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override//（Authentication）是指「哪些用户可以登陆」
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                //那我们需要在安全机制配置类方法中提供用户名的查询语句和角色权限的查询语句，并自己完成数据库中相关建表的工作
                .usersByUsernameQuery("SELECT username,password,enabled " + " FROM user_accounts WHERE username=?")
                .authoritiesByUsernameQuery("SELECT username, role " + " FROM user_accounts WHERE username = ?")
                .passwordEncoder(bCryptPasswordEncoder);

    }



    @Override//（Authentication）是指「哪些用户可以登陆」
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
               //定义「/projects/new」路径的访问需要「ADMIN」角色，而「/」路径则是已经被允许访问（.authenticated()）
//               .antMatchers("/projects/new").hasRole("ADMIN")
//               .antMatchers("/projects/save").hasRole("ADMIN")
//               .antMatchers("/students/new").hasRole("ADMIN")
////               .antMatchers("/students/save").hasRole("ADMIN")
               .antMatchers("/","/**").permitAll()
               //默认登录路径.formLogin()表示使用默认的表单登陆验证。
               .and().formLogin();

    }
}
